﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Linq;
using SuperSimpleWebshop.Common;
using SuperSimpleWebshop.Domain;
using SuperSimpleWebshop.Domain.Interfaces;
using umbraco.BusinessLogic;

namespace SuperSimpleWebshop.Payment.MultiSafePay
{
    public class MultiSafePayPaymentProvider : MultiSafePayPaymentBase, IPaymentProvider
    {
        #region IPaymentProvider Members
        public PaymentParameterRenderMethod GetParameterRenderMethod()
        {
            return PaymentParameterRenderMethod.Custom;
        }

        public List<PaymentProviderMethod> GetAllPaymentMethods(string name)
        {
            try
            {
                var helper = new PaymentConfigHelper(name);

                var gatewaysRequest = new GatewayRequest
                {
                    AccountId = long.Parse(helper.Settings["accountId"]),
                    Country = "NL",
                    SiteId = int.Parse(helper.Settings["siteId"]),
                    SiteSecureId = int.Parse(helper.Settings["siteSecureId"])
                };

                string apiURL = string.Empty;
                if (helper.TestModeEnabled)
                {
                    apiURL = helper.Settings["testURL"];
                }
                else
                {
                    apiURL = helper.Settings["url"];
                }

                var httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(apiURL);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentLength = Encoding.UTF8.GetByteCount(gatewaysRequest.GetXML());
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";

                var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
                streamWriter.Write(gatewaysRequest.GetXML());
                streamWriter.Close();

                var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Log.Add(LogTypes.Error, 0, "MultiSafePay httpWebResponse: " + httpWebResponse.ToString());
                var streamReader = new StreamReader(httpWebResponse.GetResponseStream());
                var xmlDoc = XDocument.Parse(streamReader.ReadToEnd());

                Log.Add(LogTypes.Debug, 0, "MultiSafePay xmlDoc: " + xmlDoc.ToString());

                var gateways = xmlDoc.Descendants("gateway");

                var paymentMethods = new List<PaymentProviderMethod>();
                foreach (var gateway in gateways)
                {
                    //<?xml version="1.0" encoding="UTF-8"?>
                    //<gateways result="ok">
                    //    <gateways>
                    //      <gateway>
                    //        <id>IDEAL</id>
                    //        <description>iDeal</description>
                    //      </gateway>
                    //      <gateway>
                    //        <id> MASTERCARD</id>
                    //        <description>Visa via Multipay</description>
                    //      </gateway>
                    //      <gateway>
                    //        <id> BANKTRANS</id>
                    //       <description> Bank Transfer</description>
                    //      </gateway>
                    //      <gateway>
                    //        <id> VISA</id>
                    //        <description> Visa CreditCardsdescription>
                    //      </gateway>
                    //    </gateways>
                    //</gateways>

                    int paymentImageId = 0;

                    int.TryParse(umbraco.library.GetDictionaryItem(gateway.Element("id").Value + "LogoId"), out paymentImageId);

                    paymentMethods.Add(new PaymentProviderMethod
                    {
                        Id = gateway.Element("id").Value,
                        Description = gateway.Element("description").Value,
                        Name = gateway.Element("description").Value,
                        ProviderName = GetName(),
                        ProviderNodeName = name,
                        Title = gateway.Element("description").Value,
                        ImageId = paymentImageId
                    });
                }

                return paymentMethods;
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Error, 0, "MultiSafePay.GetAllPaymentMethods: " + ex.ToString());
            }

            return null;
        }
        #endregion
    }
}
